//
//  HWNewHomeView.swift
//  HWanGame
//
//  Created by Apple on 2024/8/9.
//  Copyright © 2024 94Wan. All rights reserved.
//

import UIKit
import Stevia

//MARK: 功能区以及新游榜
class HWNewGongNengView: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource, UITableViewDelegate, UITableViewDataSource {

    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private let topView = c_make_ex(UIView.self)
        .bgColor(.white).corner(12*widthScale).end()
    private let titleLabel = c_make_ex(UILabel.self)
        .color("#1A1A1A").font(14.font_medium).text("新游榜TOP10").end()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.bounces = false
        tableView.register(HWHomeRankCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.rowHeight = 84*widthScale
        return tableView
    }()
    private let fullButton = UIIconButton(style: .trailing(itemSpace: 4))
    var clickCateBlock: ((_ cateType: String) -> Void)?
    
    var sourceData: [HWNewHomeGameModel]?{
        didSet{
            collectionView.reloadData()
        }
    }
    
    var rankArray: [HWNewHomeGameModel]?{
        didSet{
            guard let arr = rankArray, arr.count > 0 else { return }
            
            var models = [HWNewHomeGameModel]()
            for (index, md) in arr.enumerated() {
                let model = md
                model.sort = index
                models.append(model)
            }
            rankArray = models
            tableView.reloadData()
        }
    }
    
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            collectionView
            topView.subviews{
                titleLabel
                tableView
                fullButton
            }
        }
        
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 8
        layout.minimumInteritemSpacing = 8
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize(width: 55*widthScale, height: 75*widthScale)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 12*widthScale, bottom: 0, right: 0)
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(HWHomeCateCell.self, forCellWithReuseIdentifier: HWHomeCateCell.description())
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        
        fullButton.style { v in
            v.iconSize = CGSize(width: 12*widthScale, height: 12*widthScale)
            v.setImage("HomeRank_go".toImage, for: .normal)
            v.setTitle("点击查看完整榜单", for: .normal)
            v.setTitleColor("#AEB0B3".toColor, for: .normal)
            v.titleLabel?.font = 12.font_medium
            v.addTarget(self, action: #selector(clickMoreButton), for: .touchUpInside)
        }
        
        collectionView.leading(0).trailing(0).top(0).height(80*widthScale)
        topView.leading(12*widthScale).trailing(12*widthScale).height(335*widthScale)
        topView.Top == collectionView.Bottom + 15*widthScale
        titleLabel.leading(20*widthScale).top(16*widthScale)
        tableView.leading(0).trailing(0).top(40*widthScale).height(252*widthScale)
        fullButton.leading(0).trailing(0).height(32*widthScale)
        fullButton.Top == tableView.Bottom
        fullButton.addTarget(self, action: #selector(clickFullButton), for: .touchUpInside)
    }
    
    @objc private func clickFullButton(){
        NotificationCenter.default.post(name: .toAllRankListVC, object: nil)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return sourceData?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HWHomeCateCell.description(), for: indexPath) as? HWHomeCateCell else { return UICollectionViewCell() }
        cell.model = sourceData?[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let type = sourceData?[indexPath.row].type ?? ""
        clickCateBlock?(type)
//        if HWLocallyStoredData.getLoginUserID().count > 0 {
//            clickCateBlock?("")
//        }else{
//            clickCateBlock?(type)
//        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return rankArray?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "HWHomeRankCell", for: indexPath) as! HWHomeRankCell
        cell.model = rankArray?[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let infoID = rankArray?[indexPath.row].id
        let dict = ["infoID": infoID]
        NotificationCenter.default.post(name: .newGameTopToDetailVC, object: nil, userInfo: dict as [AnyHashable : Any])
    }
    
    @objc private func clickMoreButton(){

        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

//MARK: 小编推荐
class HWNewRecommendGameView: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
    
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    var dataSource: [HWNewHomeGameModel]?{
        didSet{
            collectionView.reloadData()
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        subviews{
            collectionView
        }
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize(width: 315*widthScale, height: 84*widthScale)
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(HWWuKongNormalGameCell.self, forCellWithReuseIdentifier: HWWuKongNormalGameCell.description())
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        
        collectionView.fillContainer()
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HWWuKongNormalGameCell.description(), for: indexPath) as? HWWuKongNormalGameCell else { return UICollectionViewCell() }
        cell.tuijianMd = dataSource?[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let infoID = dataSource?[indexPath.row].id
        let dict = ["infoID": infoID]
        NotificationCenter.default.post(name: .newGameTopToDetailVC, object: nil, userInfo: dict as [AnyHashable : Any])
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: 热门游戏
class HWNewHotGameView: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
    
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    var dataSource: [HWNewHomeGameModel]?{
        didSet{
            collectionView.reloadData()
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        subviews{
            collectionView
        }
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 12*widthScale
        layout.minimumInteritemSpacing = 12*widthScale
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize(width: 120*widthScale, height: 180*widthScale)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 12*widthScale, bottom: 0, right: 0)
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(HWHomeHotCell.self, forCellWithReuseIdentifier: HWHomeHotCell.description())
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        
        collectionView.top(8*widthScale).bottom(8*widthScale).leading(0).trailing(0)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HWHomeHotCell.description(), for: indexPath) as? HWHomeHotCell else { return UICollectionViewCell() }
        cell.model = dataSource?[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let infoID = dataSource?[indexPath.row].id
        let dict = ["infoID": infoID]
        NotificationCenter.default.post(name: .newGameTopToDetailVC, object: nil, userInfo: dict as [AnyHashable : Any])
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: 探索更多
class HWNewDiscoverMoreView: UITableViewCell {
    
    private let backView = c_make_ex(UIView.self)
        .corner(12*widthScale).bgColor(.white).end()
    private let topIamgeV = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color("#2E3033").font(15.font_semiBold).end()
    private let subLabel = c_make_ex(UILabel.self)
        .color("#7B7D80").font(11.font_medium).end()
    private let contentLabel = c_make_ex(UILabel.self)
        .color("#FF7500").font(12.font_medium).corner(4)
        .bgColor("#FF7500".toColor.alpha(0.08)).end()
    private let logoLabel =  c_make_ex(UILabel.self)
        .color("#FF7500").font(8.font_wide).text("77TOP")
        .alignment(.right).end()
    private let scoreLabel =  c_make_ex(UILabel.self)
        .color("#FF7500").font(16.font_wide).alignment(.right).end()
    private let colorArray = ["#FF7500","#5AB530","#36C097"]
    
    var model: HWNewHomeGameModel?{
        didSet{
            
            guard let md = model else { return }
            
            topIamgeV.sd_setImage(with: URL(string: md.image))
            nameLabel.text = md.name
            let tagStr = md.biaoqian.joined(separator: " · ")
            subLabel.text = tagStr
            scoreLabel.text = "\(md.point)"
            contentLabel.text = "  " + md.summary
            let randomInt = Int.random(in: 0...2)
            let colorString = colorArray[randomInt]
            contentLabel.textColor = colorString.toColor
            contentLabel.backgroundColor = colorString.toColor.alpha(0.08)
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        subviews{
            backView.subviews{
                topIamgeV
                nameLabel
                subLabel
                contentLabel
                logoLabel
                scoreLabel
            }
        }

        topIamgeV.layer.masksToBounds = true
        
        backView.leading(12*widthScale).trailing(12*widthScale).top(8*widthScale).height(256*widthScale)
        topIamgeV.leading(0).trailing(0).top(0).bottom(80*widthScale)
        nameLabel.leading(12*widthScale).trailing(60*widthScale)
        nameLabel.Top == topIamgeV.Bottom + 8*widthScale
        subLabel.leading(12*widthScale).trailing(60*widthScale)
        subLabel.Top == nameLabel.Bottom + 2*widthScale
        contentLabel.leading(12*widthScale).trailing(12*widthScale).height(22*widthScale)
        contentLabel.Top == subLabel.Bottom + 6*widthScale
        scoreLabel.trailing(12*widthScale).bottom(40*widthScale)
        logoLabel.trailing(12*widthScale)
        logoLabel.Bottom == scoreLabel.Top + 2*widthScale
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: 分区titileView
class HWHomeTitleHeaderView: UITableViewHeaderFooterView {
         
    private let nameLabel = c_make_ex(UILabel.self)
        .color("#1A1A1A").font(16.font_semiBold).end()
    
    var titleString: String? {
        didSet{
            guard let str = titleString else { return }
            nameLabel.text = str
        }
    }
    
    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        addSubview(nameLabel)
        
        nameLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(12*widthScale)
            make.top.equalToSuperview().offset(12*widthScale)
        }
    }
        
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
    }
    
}


//MARK: 游戏排行榜cell
class HWHomeRankCell: UITableViewCell {

    private let rankImageV = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).end()
    private let iconImageV = c_make_ex(UIImageView.self)
        .corner(12*widthScale).mode(.scaleAspectFill).end()
    private let shadowView = c_make_ex(UIView.self)
        .corner(12*widthScale).bgColor("#000000".toColor.alpha(0.1)).end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color(.black).font(14.font_semiBold).end()
    private let tagLabel = c_make_ex(UILabel.self)
        .bgColor("#E55C67".toColor.alpha(0.1)).font(8.font_medium)
        .corner(4*widthScale).color("#E55C67").end()
    private let subLabel = c_make_ex(UILabel.self)
        .color("#AEB0B3").font(13.font_semiBold).end()
    private let contentLabel =  c_make_ex(UILabel.self)
        .color("#FF7500").font(13.font_medium).end()
    private let logoLabel =  c_make_ex(UILabel.self)
        .color("#FF7500").font(8.font_wide).text("77TOP")
        .alignment(.right).end()
    private let scoreLabel =  c_make_ex(UILabel.self)
        .color("#FF7500").font(16.font_wide).alignment(.right).end()
    
    var model: HWNewHomeGameModel? {
        didSet{
            guard let md = model else { return }
            
            iconImageV.sd_setImage(with: URL(string: md.icon))
            nameLabel.text = md.name
            let tagStr = md.biaoqian.joined(separator: " · ")
            subLabel.text = tagStr
            if md.pay.count > 0 {
                tagLabel.isHidden = false
                tagLabel.text = " " + md.pay + " "
            }else{
                tagLabel.isHidden = true
            }
            contentLabel.text = md.summary
            rankImageV.image = "HomeRank_\(md.sort)".toImage
            scoreLabel.text = "\(md.point)"
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            rankImageV
            iconImageV
            nameLabel
            tagLabel
            subLabel
            contentLabel
            logoLabel
            scoreLabel
        }
        
        rankImageV.leading(20*widthScale).size(32*widthScale).centerVertically()
        iconImageV.leading(64*widthScale).size(60*widthScale).centerVertically()
        nameLabel.leading(136*widthScale).trailing(>=80).top(15*widthScale)
        tagLabel.height(15*widthScale)
        tagLabel.Leading == nameLabel.Trailing + 3*widthScale
        tagLabel.CenterY == nameLabel.CenterY
        subLabel.leading(136*widthScale).trailing(50*widthScale)
        subLabel.Top == nameLabel.Bottom + 3*widthScale
        contentLabel.leading(136*widthScale).trailing(60*widthScale)
        contentLabel.Top == subLabel.Bottom + 3*widthScale
        logoLabel.trailing(12*widthScale).top(25*widthScale)
        scoreLabel.trailing(12*widthScale)
        scoreLabel.Top == logoLabel.Bottom - 2
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

//MARK: 热门cell
class HWHomeHotCell: UICollectionViewCell {

    private let bgView = c_make_ex(UIView.self)
        .corner(12*widthScale).bgColor(.white).end()
    private let topImageV = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).bgColor(.white).end()
    private let iconImageV = c_make_ex(UIImageView.self)
        .corner(12*widthScale).mode(.scaleAspectFill).end()
    private let shadowView = c_make_ex(UIView.self)
        .gradientColors(.topToBottom([.white.alpha(0),.white])).end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color(.black).font(14.font_semiBold).alignment(.center).end()
    private let scoreLabel = UIIconButton(style: .leading(itemSpace: 2))
    private let infoLabel =  c_make_ex(UILabel.self)
        .color("#2E3033").font(12.font_semiBold).text("详情").alignment(.center)
        .border("#2E3033", width: 1.5).corner(13*widthScale).end()
    
    var model: HWNewHomeGameModel? {
        didSet{
            guard let md = model else { return }
            
            topImageV.sd_setImage(with: URL(string: md.image))
            iconImageV.sd_setImage(with: URL(string: md.icon))
            nameLabel.text = md.name
            scoreLabel.setTitle("\(md.point)", for: .normal)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = .clear
        backgroundColor = .clear
        
        contentView.subviews{
            bgView.subviews{
                topImageV
                shadowView
                iconImageV
                nameLabel
                scoreLabel
                infoLabel
            }
        }

        scoreLabel.style { v in
            v.iconSize = CGSize(width: 14*widthScale, height: 14*widthScale)
            v.setImage("ScoreStar".toImage, for: .normal)
            v.setTitleColor("#FF7500".toColor, for: .normal)
            v.titleLabel?.font = 12.font_medium
            v.isUserInteractionEnabled = false
        }
        
        bgView.fillContainer()
        topImageV.leading(0).trailing(0).top(0).height(80*widthScale)
        shadowView.leading(0).trailing(0).top(0).height(80*widthScale)
        iconImageV.size(60*widthScale).top(24*widthScale).centerHorizontally()
        nameLabel.leading(5).trailing(5)
        nameLabel.Top == iconImageV.Bottom + 8*widthScale
        scoreLabel.leading(5).trailing(5).height(15*widthScale)
        scoreLabel.Top == nameLabel.Bottom + 8*widthScale
        infoLabel.width(60*widthScale).height(26*widthScale).centerHorizontally()
        infoLabel.Top == scoreLabel.Bottom + 8*widthScale
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        shadowView.rae.gradientColors(.topToBottom([UIColor.white.alpha(0),UIColor.white]))
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
